<template>
  <div class="add-in-storage">
    <el-card>
      <div class="form-title">新增出库单</div>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="出库单号">
              <el-input
                v-model="form.warehouse_Code"
                placeholder="可不填写，自动生成"
                :readonly="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出库单类型" prop="warehousing_Type">
              <el-select
                v-model="form.warehousing_Type"
                placeholder="请选择出库类型"
              >
                <el-option label="销售出库" value="销售出库" />
                <el-option label="生产领用出库" value="生产领用出库" />
                <el-option label="领用退还出库" value="领用退还出库" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关联订单号">
              <el-input v-model="form.orderCode" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商编号" prop="supplierCode">
              <el-input
                v-model="form.supplierCode"
                placeholder="请双击选择供应商"
                @dblclick="onSupplierCodeDblClick"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商名称" prop="supplierName">
              <el-input v-model="form.supplierName" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商联系人">
              <el-input v-model="form.supplier_Contacts" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商联系方式" prop="supplier_Phone">
              <el-input v-model="form.supplier_Phone" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仓库">
              <el-select v-model="form.warehouse_ID" placeholder="请选择仓库">
                <el-option
                  v-for="item in warehouseList"
                  :label="item.warehouse_Name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制单人">
              <el-input v-model="form.createUseName" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制单时间">
              <el-date-picker
                v-model="form.createTime"
                type="date"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="form.notes"
                type="textarea"
                :rows="2"
                maxlength="300"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card style="margin-top: 20px">
      <template #header>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <span class="form-title">出库产品信息</span>
          <el-button type="primary" @click="fetchProductOptions"
            >新增产品</el-button
          >
        </div>
      </template>
      <el-table :data="productList" border>
        <el-table-column type="selection" width="50" />
        <el-table-column prop="productName" label="产品名称" />
        <el-table-column prop="productCode" label="产品编码" />
        <el-table-column prop="specifications" label="规格" />
        <el-table-column prop="batch" label="批次">
          <template #default="scope">
            <el-input v-model="scope.row.batch" placeholder="输入批次" />
          </template>
        </el-table-column>
        <el-table-column prop="price" label="单价">
          <template #default="scope">
            <el-input
              v-model="scope.row.price"
              placeholder="输入单价"
              @input="updateTotalPrice(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="warehouse_InOrOutCount" label="出库数">
          <template #default="scope">
            <el-input
              v-model="scope.row.warehouse_InOrOutCount"
              placeholder="输入出库数量"
              @input="updateTotalPrice(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="total_Price" label="总价">
          <template #default="scope">
            <el-input v-model="scope.row.total_Price" placeholder="输入总价" />
          </template>
        </el-table-column>
        <el-table-column prop="storage_ID" label="库位">
          <template #default="scope">
            <el-select v-model="scope.row.storage_ID" placeholder="选择库位">
              <el-option
                v-for="item in storageList"
                :key="item.id"
                :label="item.storage_Name"
                :value="item.id"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button type="text" @click="removeProduct(scope.$index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div style="text-align: center; margin-top: 30px">
      <el-button type="primary" @click="onSubmit">提交</el-button>
      <el-button @click="onCancel">取消</el-button>
    </div>

    <!-- 选择产品弹窗 -->
    <el-dialog v-model="showProductDialog" title="选择产品" width="80%">
      <!-- 查询区域 -->
      <div style="margin-bottom: 10px; display: flex; align-items: center">
        <el-input
          v-model="searchForm.product_Number"
          placeholder="请输入编码"
          style="width: 180px; margin-right: 10px"
        />
        <el-input
          v-model="searchForm.product_Name"
          placeholder="请输入名称"
          style="width: 180px; margin-right: 10px"
        />
        <el-button type="primary" @click="fetchProductOptions">搜索</el-button>
      </div>
      <!-- 商品表格 -->
      <el-table
        :data="productOptions"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="product_Number" label="产品编码" />
        <el-table-column prop="product_Name" label="产品名称" />
        <el-table-column prop="specifications" label="规格" />
        <el-table-column prop="category_Name" label="类别" />
        <el-table-column prop="storage_Unit" label="存储单位" />
        <el-table-column prop="packaging_Type" label="包装类型" />
        <el-table-column prop="price" label="单价" />
        <el-table-column prop="weight" label="重量" />
      </el-table>
      <table>
        <tr>
          <td>
            <el-pagination
              v-model:current-page="pageQuery1.pageindex"
              v-model:page-size="pageQuery1.pagesize"
              :page-sizes="[15, 20, 30]"
              :size="size"
              background="true"
              layout="slot, sizes"
              :total="pageQuery1.totalCount"
            >
              共{{ pageQuery1.totalCount }}条 每页显示{{
                pageQuery1.pagesize
              }}条 当前第{{ pageQuery1.pageindex }}页/共{{
                pageQuery1.totalPage
              }}页
            </el-pagination>
          </td>
          <td>
            <el-pagination
              v-model:current-page="pageQuery1.pageindex"
              v-model:page-size="pageQuery1.pagesize"
              :page-sizes="[15, 20, 30]"
              :size="size"
              background="true"
              layout="slot, prev, pager, next"
              :total="pageQuery1.totalCount"
              prev-text="上一页"
              next-text="下一页"
            >
              <el-button
                :disabled="pageQuery1.pageindex == 1"
                @click="pageQuery1.pageindex = 1"
                >首页</el-button
              >
            </el-pagination>
          </td>
          <td>
            <el-pagination
              v-model:current-page="pageQuery1.pageindex"
              v-model:page-size="pageQuery1.pagesize"
              :page-sizes="[15, 20, 30]"
              :size="size"
              background="true"
              layout="slot,jumper"
              :total="pageQuery1.totalCount"
            >
              <el-button
                :disabled="pageQuery1.pageindex == pageQuery1.totalPage"
                @click="pageQuery1.pageindex = pageQuery1.totalPage"
                >尾页</el-button
              >
            </el-pagination>
          </td>
        </tr>
      </table>
      <template #footer>
        <el-button @click="showProductDialog = false">关闭</el-button>
        <el-button type="primary" @click="onSelectProducts">选择</el-button>
      </template>
    </el-dialog>
    <!-- 选择供应商弹窗 -->
    <el-dialog v-model="showSupplierDialog" title="选择供应商" width="80%">
      <div style="margin-bottom: 10px; display: flex; align-items: center">
        <el-input
          v-model="supplierQuery.supplierCode"
          placeholder="请输入供应商编码"
          style="width: 180px; margin-right: 10px"
        />
        <el-input
          v-model="supplierQuery.supplierName"
          placeholder="请输入供应商名称"
          style="width: 180px; margin-right: 10px"
        />
        <el-button type="primary" @click="fetchSupplierList">搜索</el-button>
      </div>
      <el-table
        :data="supplierList"
        @row-dblclick="onSupplierSelect"
        highlight-current-row
      >
        <el-table-column prop="supplier_Number" label="供应商编号" />
        <el-table-column prop="supplier_Name" label="供应商名称" />
        <el-table-column prop="phone" label="电话" />
        <el-table-column prop="fax" label="传真" />
        <el-table-column prop="email" label="Email" />
        <el-table-column prop="contacts" label="联系人" />
        <el-table-column prop="address" label="地址" />
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button type="text" @click="onSupplierSelect(scope.row)"
              >选择</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <table>
        <tr>
          <td>
            <el-pagination
              v-model:current-page="pageQuery.pageindex"
              v-model:page-size="pageQuery.pagesize"
              :page-sizes="[15, 20, 30]"
              :size="size"
              background="true"
              layout="slot, sizes"
              :total="pageQuery.totalCount"
            >
              共{{ pageQuery.totalCount }}条 每页显示{{ pageQuery.pagesize }}条
              当前第{{ pageQuery.pageindex }}页/共{{ pageQuery.totalPage }}页
            </el-pagination>
          </td>
          <td>
            <el-pagination
              v-model:current-page="pageQuery.pageindex"
              v-model:page-size="pageQuery.pagesize"
              :page-sizes="[15, 20, 30]"
              :size="size"
              background="true"
              layout="slot, prev, pager, next"
              :total="pageQuery.totalCount"
              prev-text="上一页"
              next-text="下一页"
            >
              <el-button
                :disabled="pageQuery.pageindex == 1"
                @click="pageQuery.pageindex = 1"
                >首页</el-button
              >
            </el-pagination>
          </td>
          <td>
            <el-pagination
              v-model:current-page="pageQuery.pageindex"
              v-model:page-size="pageQuery.pagesize"
              :page-sizes="[15, 20, 30]"
              :size="size"
              background="true"
              layout="slot,jumper"
              :total="pageQuery.totalCount"
            >
              <el-button
                :disabled="pageQuery.pageindex == pageQuery.totalPage"
                @click="pageQuery.pageindex = pageQuery.totalPage"
                >尾页</el-button
              >
            </el-pagination>
          </td>
        </tr>
      </table>
      <template #footer>
        <el-button @click="showSupplierDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from "vue";
import { useRouter, useRoute } from "vue-router";

import { statementRed } from "@/http/axiosHelper";
import { statementWrite } from "@/http/axiosHelper";

import type { ComponentSize } from "element-plus";
import type { FormRules, FormInstance } from "element-plus";
const size = ref<ComponentSize>("default");
import axios from "axios";
import { StorageRed, StorageWrite } from "@/http/axiosHelper";
import { ElMessage } from "element-plus";

const router = useRouter();
const route = useRoute();
const form: any = reactive({
  warehouseType: 2,
  warehouse_Code: "",
  warehousing_Type: "",
  orderCode: "",
  supplierCode: "",
  supplierName: "",
  supplier_Contacts: "",
  supplier_Phone: "",
  purchase_Id: null,
  sell__Id: null,
  product_Id: "",
  batch: "",
  price: "",
  warehouse_InOrOutCount: "",
  total_Price: "",
  warehouse_ID: "",
  storage_ID: "",
  notes: "",
  createUse: Number(localStorage.getItem("id")) || 0, // 用户ID（数字）
  createUseName: localStorage.getItem("userName") || "", // 用户姓名（显示用）
  createTime: new Date().toISOString().split("T")[0],
});

interface ProductItem {
  id: number;
  product_Number: string;
  product_Name: string;
  specifications: string;
  category_ID: number;
  category_Name: string;
  storage_Unit: string;
  packaging_Type: string;
  price: number;
  weight: string;
  product_ID: number;
  warehouse_InOrOutCount: number;
  total_Price: number;
  storage_ID: number;
  batch: string;
}

const productList: any = ref<ProductItem[]>([]);

// 控制弹窗显示
const showProductDialog = ref(false);

// 查询商品表单
const searchForm = ref({
  product_Number: "",
  product_Name: "",
});

// 商品数据（实际应从接口获取）
const productOptions = ref([]);

// 获取商品列表
function fetchProductOptions() {
  showProductDialog.value = true;
  StorageRed({
    url: "/api/Warehouse_InOrOut/GetPurchase_Model",
    method: "get",
    params: {
      product_Number: searchForm.value.product_Number,
      product_Name: searchForm.value.product_Name,
      pageindex: pageQuery1.pageindex,
      pagesize: pageQuery1.pagesize,
    },
  }).then((res) => {
    productOptions.value = res.data.data;
    pageQuery1.totalCount = res.data.totalCount;
    pageQuery1.totalPage = res.data.totalPage;
  });
}

// 选中的商品
const selectedProducts = ref<ProductItem[]>([]);

// 修改 handleSelectionChange，确保深拷贝
function handleSelectionChange(val: ProductItem[]) {
  selectedProducts.value = val.map((item) => ({ ...item })); // 深拷贝
}

// 批量添加到出库产品表格
function onSelectProducts() {
  // 使用Set来快速检查重复项
  const existingProductNumbers = new Set(
    productList.value.map((item: any) => item.productCode) // 使用productCode作为唯一标识
  );

  // 过滤掉已经存在于表格中的产品（基于product_Number/productCode）
  const newProducts = selectedProducts.value.filter(
    (row) => !existingProductNumbers.has(row.product_Number)
  );

  // 生成统一批次号
  const batchCode = generateBatchCode();

  // 添加新产品到表格
  productList.value.push(
    ...newProducts.map((row) => ({
      purchase_Id: row.id ?? null, // 统一用小写，且保证为数字或null
      productCode: row.product_Number,
      productName: row.product_Name,
      specifications: row.specifications,
      price: Number(row.price) || 0,
      product_ID: row.product_ID,
      warehouse_InOrOutCount: "",
      storage_ID: "",
      batch: batchCode, // 统一批次号
      total_Price: 0, // 初始化为数字0
    }))
  );

  // 重置状态
  showProductDialog.value = false;
  selectedProducts.value = [];
}

//生成出库单号
function generateWarehouseCode() {
  const now = new Date();
  const pad = (n: any) => n.toString().padStart(2, "0");
  return (
    "RK" +
    now.getFullYear() +
    pad(now.getMonth() + 1) +
    pad(now.getDate()) +
    pad(now.getHours()) +
    pad(now.getMinutes()) +
    pad(now.getSeconds())
  );
}

onMounted(() => {
  form.warehouse_Code = generateWarehouseCode();
  getWarehouseList();
});

const pageQuery: any = reactive({
  pageindex: 1,
  pagesize: 15,
  totalCount: "",
  totalPage: "",
});
const pageQuery1: any = reactive({
  pageindex: 1,
  pagesize: 15,
  totalCount: "",
  totalPage: "",
});
// 删除产品行
function removeProduct(index: any) {
  productList.value.splice(index, 1);
}
// 提交出库单
function onSubmit() {
  formRef.value?.validate((valid: boolean) => {
    if (!valid) {
      ElMessage.error("请完善必填项！");
      return;
    }
    // 生成统一批次号
    const batchCode = generateBatchCode();
    productList.value.forEach((row: any) => {
      row.batch = batchCode;
    });

    // 1. 遍历产品列表，合并表单信息
    const items = productList.value.map((row: any) => ({
      ...form, // 上部分表单信息
      // 下部分产品信息，覆盖或补充form中的同名字段
      purchase_Id: row.purchase_Id ?? null, // 统一用小写，且保证为数字或null
      product_Id: row.product_ID,
      productCode: row.product_Number,
      productName: row.product_Name,
      specifications: row.specifications,
      price: Number(row.price) || 0,
      batch: row.batch,
      warehouse_InOrOutCount: Number(row.warehouse_InOrOutCount) || 0,
      storage_ID: row.storage_ID,
      total_Price: Number(row.total_Price) || 0, // 保证为数字
      // 你还可以根据后端需要补充其它字段
    }));

    // 2. 组装参数对象
    const params = { items };

    // 3. 调用接口
    StorageWrite({
      url: "/api/Warehouse_InOrOut/CreateWarehouse_InOrOut",
      method: "post",
      data: params,
    }).then((res) => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        router.push("/Warehouse_OutView");
        return;
      } else {
        ElMessage.error(res.data.msg);
      }
    });
  });
}
function onCancel() {
  router.back();
}
// 供应商弹窗
const showSupplierDialog = ref(false);
// 供应商查询
const supplierQuery = reactive({
  supplierCode: "",
  supplierName: "",
});
// 供应商列表
const supplierList = ref([]);
// 双击文本框弹窗
function onSupplierCodeDblClick() {
  showSupplierDialog.value = true;
  fetchSupplierList();
}
// 查询供应商
function fetchSupplierList() {
  StorageRed({
    url: "/api/Warehouse_InOrOut/GetSupplier",
    method: "get",
    params: {
      supplierCode: supplierQuery.supplierCode,
      supplierName: supplierQuery.supplierName,
      pageindex: pageQuery.pageindex,
      pagesize: pageQuery.pagesize,
    },
  }).then((res) => {
    supplierList.value = res.data.data;
    pageQuery.totalCount = res.data.totalCount;
    pageQuery.totalPage = res.data.totalPage;
  });
}

// 选择供应商
function onSupplierSelect(row: any) {
  form.supplierCode = row.supplier_Number; // 供应商编码
  form.supplierName = row.supplier_Name; // 供应商名称
  form.supplier_Contacts = row.contacts; // 供应商联系人
  form.supplier_Phone = row.phone; // 供应商联系方式
  showSupplierDialog.value = false;
}
// 仓库列表
const warehouseList: any = ref([]);
// 获取仓库列表
const getWarehouseList = () => {
  StorageRed({
    url: "/api/Warehouse_InOrOut/GetWarehouseModel",
    method: "get",
  }).then((res) => {
    warehouseList.value = res.data.data;
  });
};
// 库位列表
const storageList: any = ref([]);
// 获取库位列表
const getStorageList = () => {
  StorageRed({
    url: "/api/Warehouse_InOrOut/GetStorageModel",
    method: "get",
    params: {
      warehouse_ID: form.warehouse_ID,
    },
  }).then((res) => {
    storageList.value = res.data.data;
  });
};

// 监听仓库ID变化，自动获取库位列表
watch(
  () => form.warehouse_ID,
  (newVal) => {
    if (newVal) {
      getStorageList();
      // 清空所有产品的库位选择
      productList.value.forEach((item: any) => (item.storage_ID = ""));
    } else {
      storageList.value = [];
    }
  }
);
watch(pageQuery1, () => {
  fetchProductOptions();
});

watch(pageQuery, () => {
  fetchSupplierList();
});

function updateTotalPrice(row: any) {
  const price = Number(row.price) || 0;
  const count = Number(row.warehouse_InOrOutCount) || 0;
  row.total_Price = price * count; // 这里一定是数字
}
//生成批次号
function generateBatchCode() {
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  let result = "";
  for (let i = 0; i < 5; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
}

// 表单ref
const formRef = ref<FormInstance>();

// 校验规则
const rules: FormRules = {
  supplierCode: [
    { required: true, message: "供应商编号不能为空", trigger: "blur" },
  ],
  supplierName: [
    { required: true, message: "供应商名称不能为空", trigger: "blur" },
  ],
  supplier_Phone: [
    { required: true, message: "供应商联系方式不能为空", trigger: "blur" },
  ],
  warehousing_Type: [
    { required: true, message: "出库单类型不能为空", trigger: "change" },
  ],
};
</script>

<style scoped>
.add-in-storage {
  padding: 20px;
}
.form-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}
</style>
